import { Injectable, NotFoundException } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { CreateMenuDto } from './dto/create-menu.dto'
import { UpdateMenuDto } from './dto/update-menu.dto'
import { MenuEntity } from './entities/menu.entity'
import { Repository, SelectQueryBuilder } from 'typeorm'
import { deepClone, compose } from '../utils/util'

@Injectable()
export class MenuService {
  constructor(
    @InjectRepository(MenuEntity)
    private readonly menuRepository: Repository<MenuEntity>,
  ) { }

  // 新增菜单
  async createFirstLevelMenu(createMenuDto: CreateMenuDto) {
    const newMenu = await this.menuRepository.create({ ...createMenuDto })
    return await this.menuRepository.save(newMenu)
  }

  //新增二级菜单
  async createSecondLevelMenu(parentId: number, createMenu: CreateMenuDto) {
    const parentMenu = await this.menuRepository.findOne({ where: { id: parentId } })
    if (!parentMenu) {
      throw new Error(`Parent menu with ID ${parentId} not found`)
    }
    const newMenu = this.menuRepository.create({
      ...createMenu,
      first_menu: 0,
      parent: parentMenu
    })

    return await this.menuRepository.save(newMenu)
  }



  //获取所有菜单
  async findAll() {
    let menuData = await this.menuRepository.find({ relations: ['children'] })
    let copyMenu = deepClone(menuData)
    copyMenu.forEach((item) => {
      if (item.first_menu) {
        copyMenu = compose(item, copyMenu)
      }
    })
    return copyMenu
  }

  //根据ids 获取菜单
  async getMenusByIds(menuIds: (string | number)[]): Promise<MenuEntity[]> {
    const queryBuilder: SelectQueryBuilder<MenuEntity> = this.menuRepository.createQueryBuilder('menu')
    let menus = await queryBuilder.where('menu.id IN (:...ids)', { ids: menuIds }).getMany()
    return menus
  }


  //修改菜单
  async updateMenu(updateMenuDto: UpdateMenuDto) {
    const { id, ...menuData } = updateMenuDto;
    const menu = await this.menuRepository.findOne({ where: { id } });
    if (!menu) throw new Error('菜单不存在');
    Object.assign(menu, menuData)
    let result = await this.menuRepository.save(menu);
    return result
  }

  //根据id 查询所有子菜单一起删除
  // async getByRootId(id) {
  //   const menu = await this.menuRepository.find({ where: { id }, relations: ['children'] })
  //   let copyMenu = this.deepClone(menu)
  //   if (copyMenu.children && copyMenu.children.length > 0) {
  //     copyMenu.children.forEach((child) => {
  //       this.getByRootId(child.id)
  //     })
  //   }
  //   this.menuRepository.remove(menu)
  // }

  //删除菜单
  async removeMenuById(id: number) {
    // 找到要删除的菜单（包括其子菜单）级联删除
    const menu = await this.menuRepository.findOne({ where: { id } })
    // const menu = await this.menuRepository.find({ where: { id }, relations: ['children'] })
    if (menu) {
      // await this.getByRootId(id)
      await this.menuRepository.remove(menu)
      return {}
    } else {
      throw new NotFoundException(`Menu with ID ${id} not found.`)
    }
  }
}
